package com.bida.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bida.constant.MessageConstant;
import com.bida.constant.StatusConstant;
import com.bida.context.BaseContext;
import com.bida.domain.dto.EmployeeDTO;
import com.bida.domain.dto.EmployeeLoginDTO;
import com.bida.domain.dto.PasswordEditDTO;
import com.bida.domain.entity.Employee;
import com.bida.exception.AccountLockedException;
import com.bida.exception.AccountNotFoundException;
import com.bida.exception.BaseException;
import com.bida.exception.PasswordErrorException;
import com.bida.mapper.EmployeeMapper;
import com.bida.result.PageResult;
import com.bida.result.Result;
import com.bida.service.IEmployeeService;
import com.bida.utils.Md5Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

import static com.bida.constant.MessageConstant.*;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService  {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 需要进行md5加密，然后再进行比对
        password = Md5Utils.hash(password);
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus().equals(StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }
    /**
     * 新增员工
     * @param
     * @return
     */
    @Override
    public Result saveNewEmployee(EmployeeDTO employeeDTO) {
        // 获取当前登录用户id
        Long userId = BaseContext.getCurrentId();

        Employee employee = new Employee();
        employee.setUsername(employeeDTO.getUsername());
        employee.setName(employeeDTO.getName());
        employee.setPassword(Md5Utils.hash("123456"));
        employee.setPhone(employeeDTO.getPhone());
        employee.setSex(employeeDTO.getSex());
        employee.setIdNumber(employeeDTO.getIdNumber());
        employee.setStatus(StatusConstant.DISABLE);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(userId);
        employee.setUpdateUser(userId);
        this.save(employee);
        return Result.success();
    }

    /**
     * 员工分页查询
     * @param name
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Result<PageResult> pageGetEmployee(String name, Integer page, Integer pageSize) {
        IPage<Employee> nowPage = new Page<>(page,pageSize);
        QueryWrapper<Employee> employeeQueryWrapper = new QueryWrapper<>();
        if (name != null){
            employeeQueryWrapper.like("name",name);
        }
        IPage<Employee> employeeIPage = this.page(nowPage, employeeQueryWrapper);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(employeeIPage.getTotal());
        pageResult.setRecords(employeeIPage.getRecords());
        return Result.success(pageResult);
    }

    /**
     * 启用、禁用员工账号
     * @param status
     * @param id
     * @return
     */
    @Override
    public Result updateStatus(Integer status, Long id) {
        // 获取当前登录用户
        Long userId = BaseContext.getCurrentId();
        // 默认分页查到了，就已经证明了员工必然存在了
        boolean updateYes = this.lambdaUpdate()
                .set(Employee::getStatus, status)
                .set(Employee::getUpdateTime, LocalDateTime.now())
                .set(Employee::getUpdateUser, userId)
                .eq(Employee::getId, id)
                .update();
        if (!updateYes){
            throw new BaseException(UPDATE_EMPLOYEE_INFO_ERROR);
        }
        return Result.success();
    }

    /**
     * 编辑员工信息
     * @param employeeDTO
     * @return
     */
    @Override
    public Result updateEmployeeInfo(EmployeeDTO employeeDTO) {
        // 获取当前登录用户
        Long userId = BaseContext.getCurrentId();
        // 1.查询员工是否存在
        Employee employee = this.getById(employeeDTO.getId());
        if (employee == null){
            throw new BaseException(EMPLOY_NOT_EXIST);
        }
        // 复制信息到employee
        BeanUtils.copyProperties(employeeDTO,employee);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(userId);
        this.updateById(employee);
        return Result.success();
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @Override
    public Result<Employee> getEmployeeInfoById(Long id) {
        Employee employee = this.getById(id);
        if (employee == null){
            throw new BaseException(EMPLOY_NOT_EXIST);
        }
        return Result.success(employee);
    }

    /**
     * 修改密码(...肯定是自己修改的)
     * @param passwordEditDTO
     * @return
     */
    @Override
    public Result eitPasswordById(PasswordEditDTO passwordEditDTO) {
         Long empId = passwordEditDTO.getEmpId();
         String oldPassword = passwordEditDTO.getOldPassword();
         String newPassword = passwordEditDTO.getNewPassword();

        Employee employee = this.getById(empId);
        if (employee == null){
            throw new BaseException(EMPLOY_NOT_EXIST);
        }
        // 判断 新密码 和 旧密码 是否相同 ---> 感觉前端应该校验过了
        if(oldPassword.equals(newPassword)){
            throw new BaseException(PASSWORD_OLD_NEW_EQUAL);
        }
        this.lambdaUpdate()
                .set(Employee::getPassword, Md5Utils.hash(newPassword))
                .eq(Employee::getId, empId)
                .update();
        return Result.success();
    }

}
